<template>
  <Dialog :title="title" :visible="visible" class="single-column" button-text="提交" :reveal="reveal" :loading="loading" @close="handleClose" @confirm="handleConfirm">
    <div v-if="flag">
      <div class="divs">
        <p><span>{{ customer }}</span><span>女</span><span>135*****0101</span></p>
        <p>此顾客还无分诊信息</p>
        <p>
          <el-button @click="returnBtn">返回</el-button>
          <el-button @click="addTriageBtn">+增加分诊</el-button>
        </p>
      </div>
    </div>
    <div v-else>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="顾客：" prop="customerName">
          <el-autocomplete v-model="form.customerName" class="el-select-y" :fetch-suggestions="querySearch" :disabled="showTreadType" placeholder="姓名、手机号、编号" @select="handleSelects" />
          <span style="color:#aaaaaa;font-size: 12px;">{{ notif }}</span>
        </el-form-item>
        <el-form-item label="分诊类型：" prop="treatType">
          <dictionary-selector class="el-select-y" code="swan_front_jzlx" :value.sync="form.treatType" :disabled="showTreadType" @change="treatTypeChange" />
          <!-- <el-row>
            <el-col :span="8">
              <dictionary-selector code="swan_cutomer_yylx" :value.sync="form.appointmentType" @change="handleSelector" />
            </el-col>
            <el-col v-show="showTreadType" :span="8">
              <dictionary-selector code="swan_front_jzlx" :value.sync="form.treatType" @change="treatTypeChange" />
            </el-col>
          </el-row> -->
          <span style="color:#aaaaaa;font-size: 12px;">{{ notifTreatType }}</span>
        </el-form-item>
        <el-form-item v-if="form.treatType!=='复查'" label="咨询分类：" prop="adviserType">
          <!-- <el-cascader v-model="form.adviserType" :options="consultingOptions" :props="optionsProps" clearable /> -->
          <el-select v-model="form.adviserType" class="el-select-y" value-key="id" @change="handleSelectConsulting">
            <el-option v-for="item in consultingOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.treatType==='复查'" label="项目：" prop="intentCaseName">
          <el-select v-model="form.intentCaseName" class="el-select-y" value-key="id" @change="handleSelectProject">
            <el-option v-for="item in projectOptions" :key="item.projectId" :label="item.projectName" :value="item.projectId" />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师：" prop="adviserName">
          <el-row type="flex">
            <el-col :span="10">
              <el-select v-model="form.arrangeType" class="el-select-y" placeholder="请选择" @change="handleSeleteType(true)">
                <el-option label="轮排" value="轮排" />
                <el-option label="点排" value="点排" />
              </el-select>
            </el-col>
            <el-col :span="14">
              <el-select v-model="form.adviserName" class="el-select-y" :disabled="form.advSwitch==='开启'&&form.arrangeType==='轮排'?true:false" value-key="id" @change="handleSelectAdviserName">
                <el-option v-for="item in adviserOptions" :key="item.id" :label="item.usrName" :value="item.id" />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="主治医生：" prop="faceDoctorName">
          <el-row type="flex">
            <el-col :span="10">
              <el-select v-model="form.arrangeTypeDoc" class="el-select-y" placeholder="请选择" @change="handleSeleteType(false)">
                <el-option label="轮排" value="轮排" />
                <el-option label="点排" value="点排" />
              </el-select>
            </el-col>
            <el-col :span="14">
              <el-select v-model="form.faceDoctorName" class="el-select-y" :disabled="form.docSwitch==='开启'&&form.arrangeTypeDoc==='轮排'?true:false" value-key="id" @change="handleSelectFaceDoctorName">
                <el-option v-for="item in faceDoctorOptions" :key="item.id" :label="item.usrName" :value="item.id" />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </Dialog>
</template>

<script>
import { DictionarySelector } from "@rabbit.do/rabbit";
import Dialog from "@/components/Dialog";
export default {
  components: {
    Dialog,
    DictionarySelector,
  },
  props: {
    flag: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
    showcom: {
      type: Boolean,
      default: false,
    },
    customer: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      form: {
        treatType: '初诊',
        arrangeType: '点排',
        arrangeTypeDoc: '点排',
      },
      restaurants: [], // 顾客数据
      selectCustomerData: {}, // 选中顾客
      selectProjectData: {}, // 选中项目
      selectConsultingData: {},
      consultingOptions: [],
      adviserOptions: [],
      faceDoctorOptions: [],
      projectOptions: [],
      seleteCustomerInData: {}, // 查询顾客所有信息
      notif: "",
      notifTreatType: "",
      // optionsProps: {
      //   children: 'children',
      //   label: 'deptName',
      //   value: 'deptName',
      //   checkStrictly: true, // 选择任意一项
      // },
      // typeVal: '',
      reveal: true,
      loading: false,
      currentUserInfo: {},
      showTreadType: false,
      rules: {
        customerName: [
          { required: true, message: '请输入顾客名称', trigger: 'change' },
        ],
        treatType: [
          { required: true, message: '请选择分诊类型', trigger: 'change' },
        ],
        adviserType: [
          { required: true, message: '请选择咨询分类', trigger: 'change' },
        ],
        intentCaseName: [
          { required: true, message: '请选择项目', trigger: 'change' },
        ],
        // adviserName: [
        //   { required: true, message: '请选择咨询师', trigger: 'change' },
        // ],
      },
    };
  },
  mounted() {
    this.getSwitchState();
    this.loadAll();
    this.getConsultingData();
    this.getAdviserData();
    this.getFaceDoctorData();
    this.getProjectData();
    this.getCurrentUserInfo();
  },
  methods: {
    async getSwitchState() {
      const res = await this.$api['reception/triage/getSwitch']();
      if (res.code !== 200) return this.$message.error(res.msg);
      this.form.advSwitch = res.data.advSwitch;
      this.form.docSwitch = res.data.docSwitch;
    },
    getCurrentUserInfo() {
      this.currentUserInfo = { accepterName: this.$store.getters.name, accepterId: this.$store.getters.id };
    },
    async addTriageBtn(row) {
      this.showTreadType = false;
      this.flag = false;
      this.getSwitchState();
      this.reveal = true;
      console.log("增加分诊", row);
      if (row) {
        this.form = row;
        if (row.appointmentType === '现场咨询') {
          this.form.adviserType = row.advisoryClassification;
          this.form.adviserName = row.receiverName;
          // this.showTreadType = true;
        }
        // else {
        //   this.form.faceDoctorName = row.receiverName;
        // }
        const res = await this.$api['reception/triage/getCustomerMessageById']({ id: row.customerId });
        if (res.code === 200) {
          this.form.treatType = res.data.history;
        }
      }
    },
    editTriageBtn(row) {
      this.form = row;
      this.getSwitchState();
      // this.form.adviserType = row.advisoryClassification;
      // this.form.adviserName = row.receiverName;
      this.reveal = true;
      this.showTreadType = true;
    },
    async notTriage() {
      this.reveal = false;
      // console.log(this.customer, '根据顾客名字查询顾客详情');
      // if (this.customer && this.customer !== '') {
      //   const res = await this.$api['reception/triage/createTriage']({ ...this.form, ...this.currentUserInfo });
      //   console.log(res);
      // }
    },
    // 返回
    returnBtn() {
      this.$emit('update:visible', false);
      // this.$emit('update:flag', false);
    },
    handleConfirm() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          if (this.title === "增加分诊") {
            this.loading = true;
            const res = await this.$api['reception/triage/createTriage']({ ...this.form, ...this.currentUserInfo });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('新增分诊失败！');
            this.$message.success('新增分诊成功！');
          } else {
            this.loading = true;
            const res = await this.$api['reception/triage/updataTriage']({ ...this.form, ...this.currentUserInfo });
            this.loading = false;
            if (res.code !== 200) return this.$message.error('修改分诊失败！');
            this.$message.success('修改分诊成功！');
          }
          this.$emit('update:visible', false);
          this.$emit('success');
          this.$refs.formRef.resetFields();
        }
      });
    },
    handleClose() {
      this.$emit('update:visible', false);
      this.$emit('update:showcom', false);
      this.$emit('dialogClose');
      this.form = { treatType: '初诊', arrangeType: '点排', arrangeTypeDoc: '点排' };
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
      // this.$refs.formRef.resetFields();
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        if (restaurant) {
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          );
        }
      };
    },
    handleSelects(item) {
      this.notif = "";
      this.notifTreatType = "";
      this.form.customerId = item.id;
      this.form.customerName = item.name;
      this.form.customerCode = item.code;
      this.form.customerSex = item.sex;
      this.form.customerPhone = item.phone;
      this.form.source = item.informationSources;
      this.$set(item, 'customerId', item.id);
      this.getAllCustomerInformation(item);
    },
    // 获取选中顾客所有信息
    async getAllCustomerInformation(item) {
      if (item.customerId) {
        const res = await this.$api['reception/triage/getCustomerMessageById']({ id: item.customerId });
        if (res.code !== 200) return this.$message.error(res.msg);
        this.projectOptions = res.data.list;
        this.seleteCustomerInData = res.data;
      }
      if (this.seleteCustomerInData.history) {
        this.form.treatType = this.seleteCustomerInData.history;
      } else {
        this.form.treatType = '初诊';
      }
      // 顾客当日预约类型
      if (this.seleteCustomerInData.appointmentType === '咨询预约') {
        this.form.adviserType = this.seleteCustomerInData.advisoryClassification;
        this.form.adviserId = this.seleteCustomerInData.attributionConsultantId;
        this.form.adviserName = this.seleteCustomerInData.attributionConsultantName;
      } else if (this.seleteCustomerInData.appointmentType === '治疗预约' || this.seleteCustomerInData.appointmentType === '手术预约') {
        if (this.seleteCustomerInData.list.length > 0) {
          this.seleteCustomerInData.list.map(item => {
            item.id = item.projectId;
            item.name = item.projectName;
          });
        }
        this.projectOptions = this.seleteCustomerInData.list;
        this.form.adviserId = this.seleteCustomerInData.attributionConsultantId;
        this.form.adviserName = this.seleteCustomerInData.attributionConsultantName;
        this.form.faceDoctorName = this.seleteCustomerInData.faceDoctorName;
        this.form.treatType = '复查';
        this.form.arrangeType = '点排';
        this.form.arrangeTypeDoc = '点排';
        if (this.seleteCustomerInData.appointmentType === '手术预约') {
          this.notif = "该顾客今日有手术预约,已智能填入";
        }
      }
      // 顾客有归属咨询师时
      if (this.seleteCustomerInData.attributionConsultantName) {
        this.form.adviserId = this.seleteCustomerInData.attributionConsultantId;
        this.form.adviserName = this.seleteCustomerInData.attributionConsultantName;
        this.form.arrangeType = '点排';
        // 预约有指定接待人时
      } else if (this.seleteCustomerInData.appointmentType && this.seleteCustomerInData.receiverName) {
        this.form.adviserId = this.seleteCustomerInData.receiverId;
        this.form.adviserName = this.seleteCustomerInData.receiverName;
        this.form.arrangeType = '点排';
      } else {
        this.form.arrangeType = '点排';
      }
      if (this.seleteCustomerInData.appointmentId) {
        // 顾客当然有预约信息
        this.$set(this.form, "appointmentId", this.seleteCustomerInData.appointmentId);
        this.notif = "该顾客今日有预约,已智能填入";
      }
      if (this.form.treatType === '复诊') {
        this.notifTreatType = "该顾客有过咨询，已智能选择复诊";
      }
      if (this.form.treatType === '再消费') {
        this.notifTreatType = "该顾客有过消费，已智能选择复诊";
      }
    },
    handleSelectConsulting(id) {
      this.form.adviserTypeId = id;
      this.consultingOptions.filter(item => {
        if (item.id === id) {
          this.form.adviserType = item.name;
          this.form.deptId = item.deptId;
          this.form.deptName = item.deptName;
        }
      });
    },
    handleSelectProject(id) {
      this.$set(this.form, 'intentCaseId', id);
      this.projectOptions.filter(item => {
        if (item.projectId === id) {
          console.log(item, 'sosp');
          this.$set(this.form, 'intentCaseName', item.projectName);
          this.$set(this.form, 'intentCaseNo', item.no);
          this.$set(this.form, 'intentCaseType', item.productAttributes);
          this.$set(this.form, 'deptId', item.deductionDeptId);
          this.$set(this.form, 'deptName', item.deductionDeptName);
        }
      });
    },
    handleSelectAdviserName(id) {
      this.form.adviserId = id;
      this.adviserOptions.filter(item => {
        if (item.id === id) {
          this.form.adviserName = item.usrName;
        }
      });
    },
    handleSelectFaceDoctorName(id) {
      this.form.faceDoctorId = id;
      this.faceDoctorOptions.filter(item => {
        if (item.id === id) {
          this.form.faceDoctorName = item.usrName;
        }
      });
      this.$forceUpdate();
    },
    handleSeleteType(bool) {
      if (bool) {
        if (this.form.advSwitch === '开启' && this.form.arrangeType === '轮排' && this.form.adviserName) {
          this.form.adviserName = '';
        }
      } else {
        if (this.form.docSwitch === '开启' && this.form.arrangeTypeDoc === '轮排' && this.form.faceDoctorName) {
          this.form.faceDoctorName = '';
        }
      }
    },
    async loadAll() {
      // 所有顾客详情
      const res = await this.$api['reception/subscribe/findall']();
      if (res.code === 200) {
        res.data.map(item => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    async getConsultingData() {
      // 咨询分类
      const consultingData = await this.$api['reception/subscribe/consulttype']();
      if (consultingData.code === 200) {
        this.consultingOptions = consultingData.data.result;
      }
    },
    async getAdviserData() {
      // 咨询师
      const adviserData = await this.$api['reception/triage/AllByJobName']({ hospitalJobName: '咨询师' });
      if (adviserData.code === 200) {
        this.adviserOptions = adviserData.data;
      }
    },
    async getFaceDoctorData() {
      // 主治医生
      const faceDoctorData = await this.$api['reception/triage/AllByJobName']({ hospitalJobName: '主治医生' });
      if (faceDoctorData.code === 200) {
        this.faceDoctorOptions = faceDoctorData.data;
      }
    },
    async getProjectData() {
      // 意向项目
      // const projectData = await this.$api['reception/triage/findAll']();
      // if (projectData.code === 200) {
      //   this.projectOptions = projectData.data;
      // }
    },
    // handleSelector(val) {
    //   if (val === '复查') {
    //     if (!this.form.oldTreatType) {
    //       this.form.oldTreatType = this.form.treatType;
    //     }
    //     this.form.treatType = this.form.appointmentType;
    //     // this.showTreadType = false;
    //   } else {
    //     this.form.treatType = this.form.oldTreatType;
    //     // this.showTreadType = true;
    //   }
    // },
    treatTypeChange(val) {
      this.form.oldTreatType = val;
    },
  },
};
</script>
<style lang="scss" scoped>
.divs {
  text-align: center;
  span {
    margin: 0 20px;
  }
}
::v-deep .el-autocomplete {
  width: 100%;
}
/deep/.el-icon-circle-close.el-select__caret.el-input__icon{
  color: #9baed3 !important;
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
